// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

/*
 * @Author: qiulin_JXGM ql1746365080@gmail.com
 * @Date: 2024-10-11 15:36:29
 * @LastEditors: qiulin 1746365080@qq.com
 * @LastEditTime: 2024-12-23 14:48:57
 * @FilePath: \SGFEM\Import\BDFImport\BulkData\Constraint\SPCADDParser.cpp
 */

#include "Import/BDFImport/BulkData/Constraint/SPCADDParser.h"

#include <algorithm>
#include <iostream>

#include "Utility/Logging/SGLogger.h"

#include "DBManager/DBServiceFactory.h"
#include "DBManager/IService/Input/Constraint/ISPCADDService.h"

#include "Import/BDFImport/BDFParserBase.h"

BULKDATA_ENTRY_PARSER_REG (SPCADD);

using namespace SG::DBManager;
using namespace SG::Import;
using namespace SG::DataStructure;
/*
// file://./../../Doc/MarkDown/BulkData/SPCADD/SPCADD.md>
*/

SG::DataStructure::Common::Status BDF::BULKDATA::ParseSPCADD (const std::shared_ptr<SG::DBManager::DBServiceFactory>& dbServiceFactory,
                                                              std::vector<std::string>&                               dividedEntryInfo)
{
    // 定义 SPCADDData 类型的临时对象，用于存储解析出来的单点约束集合数据
    SG::DataStructure::FEM::SPCADDData tempData;

    // TODO(bug 001) 填写正确的 m_dominID 值，目前暂时设置为 1
    tempData.m_domainId = 1;

    // 预分配内存以存储子集数据，避免后续动态扩展
    tempData.m_subSets.reserve (dividedEntryInfo.size ());

    // 获取 SPCADD 条目的 SID，并存储在 tempData 中
    tempData.m_sId = convertToI64 (dividedEntryInfo[1]);

    // 计算行数，每行包含 10 个字段
    size_t const rowNum = dividedEntryInfo.size () / 10;

    size_t beginColumnIndex = 2;  // 从节点的第一行从index=2开始（index=1是 SID）
    // 遍历每一行条目信息
    for (size_t curRow = 0; curRow < rowNum; curRow++)
    {
        if (curRow != 0)
        {
            beginColumnIndex = 1;
        }
        // 遍历当前行的每一个字段，从第1列开始解析
        for (size_t fieldsColumn = beginColumnIndex; fieldsColumn < 9; fieldsColumn++)
        {
            // 获取当前字段的索引
            const size_t curIndex  = curRow * 10 + fieldsColumn;
            std::string& curStrKey = dividedEntryInfo[curIndex];

            // 判断当前字段是否为空，如果为空则跳过
            bool const isEmpty = is_all_space (curStrKey);
            if (isEmpty)
            {
                continue;
            }

            // 如果字段不为空，将其转换为 long long 类型并存储到 m_subSets 中
            tempData.m_subSets.push_back (convertToI64 (curStrKey));
        }
    }

    // 将解析出来的数据添加到数据库中，并返回结果
    return dbServiceFactory->get<ISPCADDService> ()->Add (tempData);
}